let goalScore = 10
let minScore = -10
let maxRound = 8

function setGameRound(game, dealer, roundNumber) {
	game.dealer = dealer
	game.roundNumber = roundNumber
	game.round = createRound(`第 ${roundNumber + 1} 局`, dealer, () => renderGame(game), () => endGameRound(game))
	console.log('Start round', game.round.name)
	playPhase(game.round)
}
function advanceGameRound(game) {
	// Check ending condition
	let ended = (game.roundNumber + 1 >= maxRound)
	for (let playerId = 0; playerId < playerCount; ++playerId) {
		if (game.points[playerId] >= goalScore || game.points[playerId] <= minScore) {
			ended = true
			break
		}
	}
	if (ended) {
		// Game ends
		game.ended = true
		renderGame(game)
	} else {
		// Game continues
		setGameRound(game, (game.dealer + 1) % playerCount, game.roundNumber + 1)
	}
}
function endGameRound(game) {
	// Update points
	for (let playerId = 0; playerId < playerCount; ++playerId) {
		game.points[playerId] += game.round.players[playerId].gain - game.round.players[playerId].loss
	}
}
let currentGame = {}
function createGame() {
	// Initial points are all zero
	currentGame = {
		points: new Array(playerCount).fill(0),
		dealer: 0,
	}
	setGameRound(currentGame, 0, 0)
}
function renderGame(game) {
	clearElements()
	addGameElement(game)
}
function loadConfig() {
	playerCount = getConfig('players')
	if (getConfig('playAsRandom')) {
		const play = Math.floor(Math.random() * playerCount)
		playing = new Array(playerCount).fill(false).map((_, i) => (i === play))
	} else {
		playing = new Array(playerCount).fill(false).map((_, i) => (!getConfig('ai' + i)))
	}
	aiDepth = getConfig('aiHard') ? 1 : 0
	goalScore = getConfig('goal')
	minScore = -getConfig('min')
	maxRound = getConfig('maxRound')
	concealTiles = getConfig('conceal')
	maxHu = getConfig('maxHu')
}
function initialize() {
	loadConfig()
	createGame()
	showMainContainer()
}